<template>
  <div>
    <template v-for="attr in attrs">
      <el-form-item v-if="value[attr.key] !== '/' && justifyFieldDep(attr.depKey, attr.depValue)" :key="attr.key" :label="attr.title">
        <el-select
          v-if="attr.type === 'select'"
          v-model="value[attr.key]"
          :disabled="disabled"
          placeholder="请选择"
          class="input"
          @change="handleChange"
        >
          <el-option
            v-for="dict in dict.type[attr.dictType]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>

        <el-date-picker
          v-else-if="['date', 'datetime'].includes(attr.type)"
          v-model="value[attr.key]"
          :disabled="disabled"
          :type="attr.type"
          placeholder="选择时间"
          class="input"
          @change="handleChange"
        />

        <el-upload
          v-else-if="attr.type === 'file'"
          list-type="picture-card"
          action="#"
          multiple
          class="input"
          :disabled="disabled"
          :file-list="value[attr.key]"
          :auto-upload="false"
          :on-preview="previewFile"
          :before-remove="beforeRemoveFile"
          :on-remove="deleteFile"
          :on-change="addFile"
        >
          <i class="el-icon-plus" />
        </el-upload>

        <el-input
          v-else
          v-model="value[attr.key]"
          :disabled="disabled"
          :type="attr.type ? attr.type : 'text'"
          class="input"
          :placeholder="attr.placeholder || '请输入内容'"
          @change="handleChange"
        />
      </el-form-item>
    </template>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { saveAs } from 'file-saver'
import { formatDatetime, isImage } from '@/utils'
import { deleteFile } from '@/api/system/file'

export default {
  name: 'SingleForm',
  props: {
    disabled: Boolean,
    value: {
      type: Object,
      default: () => ({})
    },
    dict: {
      type: Object,
      default: () => ({})
    },
    attrs: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  methods: {
    justifyFieldDep(keys, defaultValues) {
      if (typeof (keys) === 'string') {
        if (!keys) return true
        return this.value[keys] === defaultValues
      } else {
        if (!keys || !defaultValues || (keys.length !== defaultValues.length)) {
          return true
        }
        var i = 0; var len = keys.length
        for (; i < len; i++) {
          if (this.value[keys[i]] !== defaultValues[i]) {
            return false
          }
        }
        return true
      }
    },
    handleChange() {
      if (this.value.startTime) this.value.startTime = formatDatetime(this.value.startTime, 'YYYY-MM-DDTHH:mm:ss')
      this.$emit('input', this.value)
      this.$emit('change', this.value)
    },
    beforeRemoveFile(file) {
      return new Promise((resolve, reject) => {
        this.$modal.confirm(`确认删除？`).then(function() {
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    async deleteFile(file, fileList) {
      if (file.id) {
        await deleteFile(file.id)
      }
      this.value.files = fileList
      this.handleChange()
    },
    addFile(file) {
      this.value.files.push(file)
      this.handleChange()
    },
    getFileBlobUrl(file) {
      if (window.createObjectURL) {
        return window.createObjectURL(file)
      } else if (window.URL) {
        return window.URL.createObjectURL(file)
      } else if (window.webkitURL) {
        return window.webkitURL.createObjectURL(file)
      }
    },
    previewFile(file) {
      if (file.raw) {
        if (file.raw.type.includes('image')) {
          const url = this.getFileBlobUrl(file.raw)
          this.dialogImageUrl = url
          this.dialogVisible = true
        } else {
          saveAs(file.raw)
        }
      } else if (isImage(file.url.split('.').pop())) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      } else {
        saveAs(file.url)
      }
    }
  }
}
</script>

